package org.shoukaiseki.aliyun.captchasms.controller;

import org.shoukaiseki.aliyun.captchasms.constant.CaptchaSmsConstants;
import org.shoukaiseki.aliyun.captchasms.exception.CaptchaPhonenumberException;
import org.shoukaiseki.aliyun.captchasms.service.ICaptchaSmsValidateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class CaptchaPhonenumberController {


    @Value("${sks.aliyun.sms.captcha.debug:false}")
    private boolean debug=false;

    @Value("${sks.aliyun.sms.captcha.codeNumber:0}")
    private String codeNumber;

    @Autowired
    ICaptchaSmsValidateService captchaValidateService;

    /**
     * 发送验证码
     * @return
     */
    @PostMapping("/captchasms")
    @ResponseBody
    public Object captchasms(@RequestParam(CaptchaSmsConstants.CAPTCHA_SMS_PARAM_PHONENUMBER) String phonenum){
        if(debug){
            String msg="短信已发送！测试模式.验证码:";
            try{
                captchaValidateService.sendCaptcha(phonenum);
            }catch (Exception e){
               msg="测试模式.验证码:";
            }
            //获取RequestAttributes
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            //从获取RequestAttributes中获取HttpServletRequest的信息
            HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
            HttpSession session = request.getSession();
            return Map.of("code",codeNumber,"msg",msg+session.getAttribute(CaptchaSmsConstants.CAPTCHA_SMS_SESSION_ATTRNAME_CODE));

        }
        captchaValidateService.sendCaptcha(phonenum);
       return Map.of("code",codeNumber,"msg","短信已发送！");
    }


}
